﻿#include "msgsocket.h"
#include <QDataStream>

MsgSocket::MsgSocket(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
    m_tcpBlockSize = 0;
    m_tcpSocket = socket;
    connect(m_tcpSocket, SIGNAL(readyRead()),
                this, SLOT(slotReadyRead()));
}

void MsgSocket::slotReadyRead()
{
    QDataStream in(m_tcpSocket);
        in.setVersion(QDataStream::Qt_5_4);

        if(m_tcpBlockSize == 0)
        {
            if(m_tcpSocket->bytesAvailable()<sizeof(quint16))
            {
                return;
            }
            in >> m_tcpBlockSize;
        }

        if(m_tcpSocket->bytesAvailable() < m_tcpBlockSize)
        {
            return;
        }

        QString message;
        in >> message;
        qDebug() << message;
        GlobalVars::g_msgQueue.enqueue(message);//加入消息队列中

//        m_tcpSocket->disconnectFromHost();
//        m_tcpSocket->close();
        m_tcpBlockSize = 0;
}

bool MsgSocket::slotSendMsg(QString msg)
{
       QByteArray buffer;
       QDataStream out(&buffer, QIODevice::WriteOnly);
       out.setVersion(QDataStream::Qt_5_4);

       out << (quint16)0;
       out << msg;
       out.device()->seek(0);
       out << (quint16)(buffer.size() - sizeof(quint16));

        m_tcpSocket->write(buffer);
}
